/*
 * Copyright (c) 2015 LingoChamp Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.living.filedownloader.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.living.R;
import com.living.filedownloader.DownLoadManger;
import com.living.filedownloader.GlobalTaskMonitor;
import com.living.filedownloader.TasksManager;
import com.living.filedownloader.bean.TasksManagerModel;
import com.living.filedownloader.event.EventDownloadComplete;
import com.living.filedownloader.ui.adapter.TaskItemDownloadingAdapter;
import com.living.filedownloader.ui.batch.DownloadBatchActivity;
import com.living.widget.MorePopupWindow;
import com.md.livingwidget.CoreBaseActivity;
import com.md.livingwidget.emptyview.PHEmptyViewUI;
import com.md.network.api.Audio;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 正在下载的页面
 * Created by wangq
 */
public class TasksDownloadingActivity extends CoreBaseActivity implements OnItemChildClickListener {

    private TaskItemDownloadingAdapter taskItemAdapter;
    private MorePopupWindow morePopupWindow;
    private ImageView iv_download_status;
    private TextView tv_download_tip;
    private int downloadingCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_downloading_tasks);
        setToolbarTitle("正在下载");
        iv_download_status = findViewById(R.id.iv_download_status);
        tv_download_tip = findViewById(R.id.tv_download_tip);

        findViewById(R.id.iv_download_edite).setOnClickListener(this);
        iv_download_status.setOnClickListener(this);
        tv_download_tip.setOnClickListener(this);

        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        taskItemAdapter = new TaskItemDownloadingAdapter();
        recyclerView.setAdapter(taskItemAdapter);

        PHEmptyViewUI phEmptyViewUI = new PHEmptyViewUI(this);
        phEmptyViewUI.setEmptyText("没有正在下载歌曲");
        taskItemAdapter.setEmptyView(phEmptyViewUI);
        refresh();

        TasksManager.getImpl().onCreate(new WeakReference<>(this));

        morePopupWindow = new MorePopupWindow(this, new MorePopupWindow.OnMoreItemClick() {
            @Override
            public void onClickAdd(Object object) {
                TasksManagerModel audio = (TasksManagerModel) object;

            }

            @Override
            public void onClickDownload(Object object) {
                TasksManagerModel audio = (TasksManagerModel) object;
//                DownLoadManger.getInstance().downloadAudioList();
            }

            @Override
            public void onClickShare(Object object) {
                TasksManagerModel audio = (TasksManagerModel) object;
            }

            @Override
            public void onClickDelete(Object object) {
                TasksManagerModel audio = (TasksManagerModel) object;
                taskItemAdapter.remove(audio);
                DownLoadManger.getInstance().deleteAudio(audio.getAlbumId(), audio.getAudioId(), audio.getUrl());
            }
        });
        morePopupWindow.setMenuShows(true, false, true, true);
    }

    public void postNotifyDataChanged() {
        if (taskItemAdapter != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (taskItemAdapter != null) {
                        taskItemAdapter.notifyDataSetChanged();
                    }
                }
            });
        }
    }


    private void refresh() {
        List<TasksManagerModel> tasksManagerModels = DownLoadManger.getInstance().getDownloadingList();
        taskItemAdapter.setNewInstance(tasksManagerModels);
        downloadingCount = 0;
        for (TasksManagerModel task : tasksManagerModels) {
            if (task.getStatus() == FileDownloadStatus.pending || task.getStatus() == FileDownloadStatus.started || task.getStatus() == FileDownloadStatus.connected) {
                downloadingCount++;
            }
        }
        if (downloadingCount > 0) {
            iv_download_status.setImageResource(R.drawable.icon_downloading_pause);
            tv_download_tip.setText("全部暂停(" + tasksManagerModels.size() + ")");
        } else {
            iv_download_status.setImageResource(R.drawable.icon_downloaded_playall);
            tv_download_tip.setText("全部开始(" + tasksManagerModels.size() + ")");
        }
        if (tasksManagerModels.size() == 0) {
            finish();
        }
    }

    @Override
    public void onEventBase(Object event) {
        super.onEventBase(event);
        if (event instanceof EventDownloadComplete) {
            refresh();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.iv_download_edite) {
            List<TasksManagerModel> downloadedList = DownLoadManger.getInstance().getDownloadingList();
            // 进入批量删除的操作
            Intent intent = new Intent(this, DownloadBatchActivity.class);
            intent.putExtra("list", (ArrayList<TasksManagerModel>) downloadedList);
            startActivity(intent);
        } else if (v.getId() == R.id.iv_download_status || v.getId() == R.id.tv_download_tip) {
            if (downloadingCount > 0) {
                FileDownloader.getImpl().pauseAll();
            } else {
                List<TasksManagerModel> downloadingList = DownLoadManger.getInstance().getDownloadingList();
                for (TasksManagerModel tasksManagerModel : downloadingList) {
                    DownLoadManger.getInstance().startDownload(tasksManagerModel.getUrl());
                }
                taskItemAdapter.notifyDataSetChanged();
            }
        }

    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        morePopupWindow.showDialog(taskItemAdapter.getItem(position));
    }

    @Override
    protected void onDestroy() {
        taskItemAdapter = null;
//        TasksStateManagerUi.getInstance().destoryBindHolder();
//        FileDownloader.getImpl().pauseAll();
        super.onDestroy();
    }


}
